package inc.veluvana.weatherforecaster

/**
 *
 * @author eduarc (Eduar Castrillo)
 * @see Hardwood
 */
class OrderLoader {
  
  private static definedHardwoods = [:]
  private static defaultOrderLoader = new OrderLoader()
  
  /* Initialize the default loader */
  private OrderLoader() {
      // add standard Hardwoods
    addHardwood(Hardwood.CHERRY)
    addHardwood(Hardwood.CURLY_MAPLE)
    addHardwood(Hardwood.GENUINE_MAHOGANY)
    addHardwood(Hardwood.WENGE)
    addHardwood(Hardwood.WHITE_OAK)
    addHardwood(Hardwood.SAWDUST)
  }
  
  /**
   * @return the default order loader
   */
  static getDefaultLoader() {
    defaultOrderLoader
  }
  
  /**
   * @return the defaul OrderLoader
   */
  static getDefinedHardwoods() {
    definedHardwoods
  }
  
  /** 
   * Add a hardwood to list of available hardwoods that can be
   * loaded with this OrderLoader
   */
  static addHardwood(hardwood) {
    definedHardwoods[hardwood.cannonicalName] = hardwood
  }
  
  /** 
   * Remove a hardwood from list of available hardwoods that can be
   * loaded with this OrderLoader
   */
  static removeHardwood(hardwood) {
    definedHardwoods.remove(hardwood.cannonicalName)
  }
  
  /** 
   * Load an order from the file in the specified path.
   * The content of the file follows the next structure:
   *
   *  amount1 hardwoodCannonicalName1
   *  amount2 hardwoodCannonicalName2
   *  ...
   *  amountN hardwoodCannonicalNameN
   *  
   * @param f path of the file containing the order
   * @return the order loaded from the file; null if the specified file not exists
   **/
  static load(File f) {
    
    if (!f.exists()) {
      return null
    }
    def order = new Order()
    def sc = new Scanner(new FileInputStream(f))
    
    while (sc.hasNext()) {
      def amount = sc.nextInt()
      def hardwoodName = sc.next().toLowerCase()
      def hardwood = definedHardwoods[hardwoodName]
        // No registered hardwood
      if (!hardwood) {
        throw new Exception("Undefined hardwood type: ${hardwoodName}")
      }
      order.setAmount(hardwood, amount)
    }
    sc.close()
    order
  }
}

